package com.dongdongshop.controller;


import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Result;
import com.dongdongshop.model.TbSpecification;
import com.dongdongshop.model.TbSpecificationOption;
import com.dongdongshop.service.SpecService;
import com.dongdongshop.vo.SpecVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("spec")
public class SpecController {

    @Autowired
    private SpecService specService;


    @PostMapping
    public Result SpecList(@RequestBody SpecVo specVo){
        try {
            List<SpecVo> specVoList = specService.SpecList(specVo);
            return Result.OK().setData(specVoList);
        }catch (Exception e){
            return Result.er();
        }
    }


    @PostMapping("add")
    public Result add(SpecVo specVo , String optionListJson){
        List<TbSpecificationOption> options = JSONObject.parseArray(optionListJson, TbSpecificationOption.class);

        try {
            specService.add(specVo,options);
            return Result.OK();
        }catch (Exception e){
            return Result.er();
        }
    }


    //删除
    @PostMapping("delete")
    public Result delete(Long[] ids){
        try {
            specService.delete(ids);
            return Result.OK();
        }catch (Exception e){
            return Result.er();
        }
    }


    //查询
    @PostMapping("getBySpecId")
    public Result getBySpecId(Long id){
        try {
            SpecVo specVo = specService.getBySpecId(id);
            return Result.OK().setData(specVo);
        }catch (Exception e){
            return Result.er();
        }
    }

    @PostMapping("update")
    public Result update(TbSpecification tbSpecification, String arrStr){
        try {
            List<TbSpecificationOption> list = JSONObject.parseArray(arrStr, TbSpecificationOption.class);
            specService.update(tbSpecification,list);
            return Result.OK();
        }catch (Exception e){
            return Result.er();
        }
    }


    //获取spec数据
    @PostMapping("getspec")
    public Result getspec(){
        try {
            List<SpecVo> specifications = specService.getspec();
            return Result.OK().setData(specifications);
        }catch (Exception e){
            return Result.er();
        }
    }


}
